package com.kichina.parking.upstream;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kichina.parking.exception.extend.JsonParseException;
import com.kichina.parking.module.message.socket.enums.MessageTypeEnum;
import com.kichina.parking.service.logic.bean.ParkingRecord;
import com.kichina.parking.service.logic.service.ParkingRecordService;
import com.kichina.parking.utils.JsonToEntityUtil;
import com.kichina.parking.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author Surging
 * @version 1.0
 * @ClassName ParkingRecordUpstreamHandler
 * @date 2022-09-14 16:42
 * @desc 入场记录上传/出场记录上传业务处理
 */

@Component
@Slf4j
public class Parking1RecordUpstreamHandler {

    private final ParkingRecordService parkingRecordService;

    public Parking1RecordUpstreamHandler(ParkingRecordService parkingRecordService) {
        this.parkingRecordService = parkingRecordService;
    }

    /**
     * @param jsonObject 入场信息实体
     * @author Surging
     * @Description 入场/出场信息上传
     * 上传方式:立即上传。每次上次 只能 5 条逐条上传。
     * @Return void
     * @date 19:29 2022-09-14
     **/
    public void recordInOrOutUpstream(JSONObject jsonObject) throws JsonParseException {
        DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
        ParkingRecord parkingRecord;
        try {
            parkingRecord = JsonToEntityUtil.jsonToEntity(jsonObject, ParkingRecord.class);
            //车辆入场信息上传保存
           if (MessageTypeEnum.UPLOAD_CAR_OUT.getValue().equals(jsonObject.getString("service"))) {
                //车辆出场信息上传保存
                if (jsonObject.containsKey("out_time")) {
                    parkingRecord.setOutTime(jsonObject.getString("out_time"));
                    //日期转换
                    if(String.valueOf(jsonObject.getString("out_time")).length()<15) {
                        //字符串格式两种 2022-10-15; 2022-09-16 15:54:00;
                        parkingRecord.setOutTimeStamp(simpleDateFormat2.parse(String.valueOf(jsonObject.getString("out_time"))));
                    }else {
                        parkingRecord.setOutTimeStamp(simpleDateFormat.parse(String.valueOf(jsonObject.getString("out_time"))));
                    }
                }
            }
            if (jsonObject.containsKey("in_time")) {
                parkingRecord.setInTime(jsonObject.getString("in_time"));
                //日期转换
                if(String.valueOf(jsonObject.getString("out_time")).length()<15) {
                    parkingRecord.setInTimeStamp(simpleDateFormat2.parse(String.valueOf(jsonObject.getString("in_time"))));
                }else {
                    parkingRecord.setInTimeStamp(simpleDateFormat.parse(String.valueOf(jsonObject.getString("in_time"))));
                }
            }
            if (jsonObject.containsKey("last_login_time")) {
                parkingRecord.setLastLoginTime(jsonObject.getString("last_login_time"));
                //日期转换
                if(String.valueOf(jsonObject.getString("last_login_time")).length()<15) {
                    parkingRecord.setLastLoginTimeDate(simpleDateFormat2.parse(String.valueOf(jsonObject.getString("last_login_time"))));
                }else {
                    parkingRecord.setLastLoginTimeDate(simpleDateFormat.parse(String.valueOf(jsonObject.getString("last_login_time"))));
                }
            }
            if (Objects.nonNull(parkingRecord.getPaycharge())){
                parkingRecord.setPaychargeNum(BigDecimal.valueOf(Double.parseDouble(parkingRecord.getPaycharge())));
            }
            if (Objects.nonNull(parkingRecord.getRealcharge())){
                parkingRecord.setRealchargeNum(BigDecimal.valueOf(Double.parseDouble(parkingRecord.getRealcharge())));
            }
            if (Objects.nonNull(parkingRecord.getBreaksAmount())){
                parkingRecord.setBreaksAmountNum(BigDecimal.valueOf(Double.parseDouble(parkingRecord.getBreaksAmount())));
            }
            if (Objects.nonNull(parkingRecord.getDiscountAmount())){
                parkingRecord.setDiscountAmountNum(BigDecimal.valueOf(Double.parseDouble(parkingRecord.getDiscountAmount())));
            }
            dealDateAndAddOrUpdate(parkingRecord);
        } catch (ParseException e) {
            log.error("数据格式不合法，解析失败");
            throw new JsonParseException("数据格式不合法，解析失败");
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void dealDateAndAddOrUpdate(ParkingRecord parkingRecord) {

        //先查询 防止重复插入
        LambdaQueryWrapper<ParkingRecord> eq = new QueryWrapper<ParkingRecord>().lambda()
                .eq(ParkingRecord::getParkid, parkingRecord.getParkid())
                .eq(ParkingRecord::getOrderId, parkingRecord.getOrderId())
                .eq(ParkingRecord::getCarNumber, parkingRecord.getCarNumber())
                .eq(ParkingRecord::getInTime, parkingRecord.getInTime());
        List<ParkingRecord> list = parkingRecordService.list(eq);
        if (CollectionUtils.isNotEmpty(list)) {
            //如果不为空，先更新
            parkingRecord.setUpdateTime(new Date());
            parkingRecordService.update(parkingRecord, eq);
        } else {
            //为空，插入
            parkingRecord.setParkingRecordId(UUIDUtil.getUUID());
            parkingRecord.setUpdateTime(new Date());
            parkingRecord.setCreateTime(new Date());
            parkingRecordService.save(parkingRecord);
        }
    }
}
